Climbing Stairs

You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

题目大意:爬n级楼梯,每次可以爬1或2级,问有多少种不同的爬法

题目难度:Easy

/**
 * Created by gzdaijie on 16/5/30
 * 假设有i个2,j个1,那么可能有 (i + j)!/(i! * j!)种
 * 因此考虑可以拆分为多少个2和1即可。
 */
public class Solution {
    public int climbStairs(int n) {
        int result = 0;
        for (int i = 0; i <= n/2; i++) {
            int count = n - i;
            long tmp = 1, k = 1;
            for (int j = n - 2 * i + 1; j <= count ; j++) {
                tmp *= j;
                tmp /= k++;
            }
            result += tmp;
        }
        return result;
    }
}
gzdaijie            updated 2016-05-30 21:55:38

results matching ""

    No results matching ""